package com.lkd.handler;


import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    /**
     * 创建自动维修工单
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("采集到设备发来的数据");
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null || StringUtils.isBlank(vmStatusContract.getInnerCode()) || vmStatusContract.getStatusInfo() == null || vmStatusContract.getStatusInfo().size() <= 0){
            return;
        }
        if (vmStatusContract.getStatusInfo().stream().anyMatch(statusInfo -> statusInfo.isStatus()==false)) {
            try {
                VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                if (vmInfo == null) return;
                int userId = taskService.getLastUser(vmInfo.getRegionId(), false);
                if (userId != 0){
                    TaskViewModel taskViewModel = new TaskViewModel();
                    taskViewModel.setCreateType(0);
                    taskViewModel.setInnerCode(vmInfo.getInnerCode());
                    taskViewModel.setUserId(userId);
                    taskViewModel.setAssignorId(0);
                    taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
                    taskViewModel.setDesc("创建自动维修工单");
                    taskService.createTask(taskViewModel);
                }
            } catch (LogicException e) {
                e.printStackTrace();
                log.error("自动创建工单失败，采集到发来的信息：",jsonMsg);
            }
        }
    }
}
